package com.parktech.sun.domain.service.lucene;

import com.parktech.sun.domain.model.ContentEntity;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.SearchService;
import com.parktech.sun.web.listener.GlobalConfig;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * User: Think
 * Date: 11-1-21
 * Time: 上午1:53
 */
@Service
public class SearchServiceImpl implements SearchService {

    public Page search(String keyword, Page page) {
        try {

        Directory dir = FSDirectory.open(getIndexDir());

        IndexSearcher searcher = new IndexSearcher(dir);
//        Query query = MultiFieldQueryParser.parse(Version.LUCENE_CURRENT, new String[]{keyword, keyword},new String[]{"title", "contentText"}, new IKAnalyzer());
         Term term = new Term("contentText",keyword);
        Query query = new TermQuery(term);
        int maxDoc = searcher.maxDoc();
        TopScoreDocCollector topCollector = TopScoreDocCollector.create(maxDoc, false);
        searcher.search(query, topCollector);
        page.setTotalCount(topCollector.topDocs().totalHits);
        // 高亮设置
        SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<span class=\"key\">", "</span>");//
        Highlighter highlighter = new Highlighter(simpleHtmlFormatter,new QueryScorer(query));
        highlighter.setTextFragmenter(new SimpleFragmenter(150));
        // 查询当页的记录
        TopScoreDocCollector topOrderCollector = TopScoreDocCollector.create(maxDoc, true);
        searcher.search(query, topOrderCollector);
        ScoreDoc[] docs = topOrderCollector.topDocs((page.getPageNo() - 1) * page.getPageSize(), page.getPageSize()).scoreDocs;
        List result = new ArrayList();
        for (ScoreDoc scoreDoc : docs) {
            Document document = searcher.doc(scoreDoc.doc);
            TokenStream tokenStream = new IKAnalyzer().tokenStream("", new StringReader(document.get("contentText")));
            String str = highlighter.getBestFragment(tokenStream, document.get("contentText"));
            result.add(new ContentEntity(Long.valueOf(document.get("id")), document.get("title"), str, document.get("location")));
        }
        page.setResult(result);

        } catch (InvalidTokenOffsetsException e) {
            e.printStackTrace();
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return page;
    }

    private File getIndexDir() {
        String indexPath = GlobalConfig.getWebRoot() + "/../index";
        File indexDir = new File(indexPath);
        if (!indexDir.exists()) indexDir.mkdirs();
        return indexDir;
    }
}
